<?php
// 应用公共文件

/**
 * 数组转树形
 * @param array $list 待转换的数组
 * @param string $pk 父字段
 * @param string $pid 子字段
 * @param string $child 子节点名称
 * @param int $root
 * @return array
 */
function list_to_tree(array $list, string $pk = 'id', string $pid = 'pid', string $child = 'children', int $root = 0): array
{
    $tree = $refer = [];
    if (is_array($list)) {
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] = &$list[$key];
        }
        foreach ($list as $key => $data) {
            $parentId = $data[$pid];
            if ($root == $parentId) {
                $tree[] = &$list[$key];
            } else {
                if (isset($refer[$parentId])) {
                    $parent           = &$refer[$parentId];
                    $parent[$child][] = &$list[$key];
                }
            }
        }
    }
    return $tree;
}

/**
 * 获取系统配置信息
 * @param string $name string|null  配置名称
 * @param string|null $group string 配置分组名称
 * @return mixed 根据分组将返回array,根据名称将返回string
 */
function get_sys_config(string $name, string $group = null): mixed
{
    $value = empty($group) ? \app\common\cache\system\ConfigCache::get($name) : \app\common\cache\system\ConfigCache::get($group);
    if (empty($value)) {
        if (!empty($group)) {
            $where = ['group_code' => $group];
            $value = \app\common\model\system\ConfigModel::where($where)->column(['key', 'value']);
            $data  = [];
            foreach ($value as $v) {
                $data[$v['key']] = $v['value'];
            }
            $value = $data;
            \app\common\cache\system\ConfigCache::set($group, $value, 0);
        } else {
            $where = ['key' => $name];
            $value = \app\common\model\system\ConfigModel::where($where)->value('value');
            \app\common\cache\system\ConfigCache::set($name, $value, 0);
        }
    }
    return $value;
}

/**
 * 获取当前日期时间
 * format：Y-m-d H:i:s
 *
 * @return string
 */
function date_time(): string
{
    return date('Y-m-d H:i:s');
}